package cn.icanci.ladybird.interceptor;

import cn.icanci.ladybird.common.util.JWTUtils;
import cn.icanci.ladybird.controller.AdminController;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author: icanci
 * @date: Created in 2020/10/7 7:12
 * @classAction: 管理员的登录拦截器
 */
@SuppressWarnings("all")

public class AdminLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private AdminController adminController;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 从请求头中获取Token
            String accessToken = request.getHeader("token");
            if (null == accessToken) {
                accessToken = request.getParameter("token");
            }
            if (null == accessToken) {
                accessToken = (String) request.getSession().getAttribute("token");
            }
            if (StringUtils.isNotBlank(accessToken)) {
                Claims claims = JWTUtils.checkJWT(accessToken);
                if (null == claims) {
                    // 直接跳转到登录界面
                    // adminController.adminLogin();
                    // 告诉登录失败 重启登录
                    response.sendRedirect("/api/v1/pri/admin/login");
                    return false;
                }
                // 得到 管理员的id、权限、头像、名字
                String adminHeadImg = (String) claims.get("admin_head_img");
                Integer adminId = (Integer) claims.get("admin_id");
                Integer adminEnabled = (Integer) claims.get("admin_enabled");
                String adminName = (String) claims.get("admin_name");
                Integer admin_authority = (Integer) claims.get("admin_authority");
                // 如果不可用，就不能登录
                if (adminEnabled == 0) {
                    response.sendRedirect("/api/v1/pri/admin/403");
                    return false;
                }
                request.setAttribute("admin_head_img", adminHeadImg);
                request.setAttribute("admin_id", adminId);
                request.setAttribute("admin_enabled", adminEnabled);
                request.setAttribute("admin_name", adminName);
                request.setAttribute("admin_name", adminName);
                String authority = "管理员";
                switch (admin_authority) {
                    case 0:
                        authority = "顶级管理员";
                        break;
                    case 1:
                        authority = "一级管理员";
                        break;
                    case 2:
                        authority = "二级管理员";
                        break;
                    case 3:
                        authority = "三级管理员";
                        break;
                    default:
                        break;
                }
                request.setAttribute("admin_authority", authority);
                return true;
            }
        } catch (Exception e) {
            response.sendRedirect("/api/v1/pri/admin/login");
            return false;
        }
        response.sendRedirect("/api/v1/pri/admin/login");
        return false;
    }

    /**
     * 发送给页面
     *
     * @param response 相应
     * @param obj      需要写出的数据
     */
    private static void sendJsonMessage(HttpServletResponse response, Object obj) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print(objectMapper.writeValueAsString(obj));
            writer.close();
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
